<template>
  <v-touch
    class="mainRow"
    v-on:swipeleft="mySwipeLeft"
    v-on:swiperight="mySwipeRight"
  >
    <van-cell is-link title="组件介绍" to="/views/swiper/vue-touch/index" />
    <!-- 倒计时信息 -->
    <van-row v-show="false">
      <van-col span="6">剩余时间</van-col>
      <van-col span="14">
        <van-count-down :time="time" ref="countDownTime">
          <template #default="timeData">
            <span class="block">{{ timeData.hours }}</span>
            <span class="colon">:</span>
            <span class="block">{{ timeData.minutes }}</span>
            <span class="colon">:</span>
            <span class="block">{{ timeData.seconds }}</span>
          </template>
        </van-count-down>
      </van-col>
    </van-row>
    <!-- 操作导航栏 -->
    <van-row class="topRow" gutter="10">
      <van-col @click="goPrev()" align="right" span="10">
        <img
          :src="require('../../../assets/images/arrow.png')"
          height="30px"
          width="30px"
        />
        <span style="height: 10px; position: relative; bottom: 10px"
          >上一题</span
        >
      </van-col>
      <van-col @click="goNext()" align="right" span="8">
        <span style="height: 10px; position: relative; bottom: 10px"
          >下一题</span
        >
        <img
          :src="require('../../../assets/images/arrow-left.png')"
          height="30px"
          width="30px"
        />
      </van-col>
      <van-col align="right" span="6">
        <van-tag @click="submitAnswer" size="large" type="primary"
          >交卷</van-tag
        >
      </van-col>
    </van-row>
    <!-- 问题详细信息栏 -->
    <van-row class="questionDetailRow">
      <!-- 题目指示行 -->
      <van-row class="questionIndexRow">
        <van-col span="12">
          <van-icon color="#1989FA" name="edit"></van-icon>
          <span style="font-size: 20px">{{
            questionType[currentQuestion.questionType]
          }}</span>
        </van-col>
        <van-col align="right" span="12">
          <span>
            <label style="font-size: 0.6rem">{{ currentIndex + 1 }}</label>
            /
            {{ questionList.length }}
          </span>
        </van-col>
      </van-row>
      <van-divider
        :style="{
          borderColor: '#F2F2F2',
          padding: '0px 0px',
          margin: '0 0 0.3rem 0 '
        }"
      />
      <!-- 题目标题 -->
      <van-col class="questionTitle" span="22">
        <span>{{ currentQuestion.question }}</span>
      </van-col>
      <!-- 题目选项 @click换成@touchstart.prevent.native会影响滑动时对答案区域的选中-->
      <van-col
        :class="
          currentSelected.includes(name) ? 'selectedAnswer' : 'selectAnswer'
        "
        :key="name"
        @click="selectedAnswer(currentQuestion, name)"
        span="23"
        v-for="(value, name) in currentQuestion.options"
        >{{ name }}：{{ value.trim() }}</van-col
      >
      <!-- 题目提示信息 -->
      <van-row>
        <van-col align="left" span="24">
          <van-tag class="departmentRow" color="#E7F4F2" text-color="#29A057"
            >出题：{{ currentQuestion.submitDept }}</van-tag
          >
        </van-col>
      </van-row>
      <van-row :key="currentIndex" class="tipInfoBtnRow">
        <van-col align="right" span="24">
          <img
            height="15px "
            src="../../../assets/images/tipIcon.png"
            style="margin-right: 5px"
            width="15px"
          />
          <span @click="showTipInfoPopup">查看提示</span>
        </van-col>
      </van-row>
    </van-row>
    <van-action-sheet
      style="padding: 0px; height: 70%"
      title="提示"
      v-model="tipInfoshow"
    >
      <div style="display: block">
        <van-row class="tipInfoCurrentAnswer">
          <van-col span="24" style="height: 10%"
            >答案：{{ currentQuestion.answer }}</van-col
          >
        </van-row>
        <van-row class="tipInfoRow">{{ currentQuestion.questionNote }}</van-row>
        <!-- <van-image
          :src="require('../../../assets/images/tipInfoBg.png')"
          style="position: fixed; bottom: 0; height: 150px"
          width="100%"
        ></van-image> -->
      </div>
    </van-action-sheet>
  </v-touch>
</template>

<script>
import { getQuestionListData } from '../../../api/swiper'

export default {
  name: 'VueTouch',
  data() {
    return {
      tipPopupStyle: {
        height: '60%'
      },
      time: 60 * 60 * 1000, // 倒计时秒数
      selectAnswer: 'selectAnswer',
      selectedAnswerClass: 'selectedAnswer',
      questionList: [], //问题列表
      currentQuestion: {}, //当前题目信息
      currentIndex: 0, // 当前题目顺序索引值
      questionType: {
        //题目类型
        1: '单选题',
        2: '多选题',
        3: '填空题',
        4: '简答题'
      },
      currentTipInfo: '', //当前提示信息
      currentAnswer: '', // 当前题目答案嘻嘻你
      selected: [], //选中列表
      currentSelected: [], // 当前选中项
      tipInfoshow: false, // 提示信息弹出层
      totalScore: 0, //总分值
      totalCorrectNum: 0, //对题数量
      usedSeconds: '', //总用时
      partScoreTotal: {}, // 按题型统计分值
      partCorrectNum: {}, // 按题型统计对题数
      partCorrectTotalNum: {} //按题型统计总题数
    }
  },
  created() {
    // 获取题目数据
    this.initData()
  },
  beforeRouteLeave(to, from, next) {
    //  监听路由，若提示信息已打开，则返回按钮的效果是关闭提示信息，且阻止返回
    if (this.tipInfoshow) {
      this.tipInfoshow = false
      next(false)
    } else {
      next()
    }
  },
  methods: {
    /**
     * 初始化数据
     */
    initData() {
      this.getQuestionList()
    },
    /**
     * 获取问题列表
     */
    getQuestionList() {
      let param = {
        sessionID: this.sessionId,
        bizContent: {
          eventNo: '00001'
        }
      }
      getQuestionListData(param).then((res) => {
        let getQuestionBody = res.bizContent.questionBody
        let newQuestionList = [
          ...getQuestionBody[0].questionList,
          ...getQuestionBody[1].questionList
        ]

        newQuestionList.forEach((item) => {
          if (!(item.options instanceof Object)) {
            this.$set(item, 'options', JSON.parse(item.options))
          }
        })
        this.questionList = newQuestionList
        this.currentQuestion = this.questionList[this.currentIndex]
      })
    },
    /**
     * 校验下次索引是否越界
     */
    checkCurrentIndex(currentIndex) {
      if (currentIndex >= this.questionList.length || currentIndex < 0) {
        return false
      }
      return true
    },
    goPrev() {
      this.mySwipeRight()
    },
    goNext() {
      this.mySwipeLeft()
    },
    /**
     * 检测当前题目是否已选中
     */
    checkCurrentQuestionAnswered() {
      if (this.currentSelected.length == 0) {
        return false
      }
      return true
    },
    /**
     * 左滑事件
     */
    mySwipeLeft() {
      // 最后一题不允许左滑
      if (!this.checkCurrentIndex(this.currentIndex + 1)) {
        return
      }
      // 本题未作答，则不允许进入下一题
      if (!this.checkCurrentQuestionAnswered()) {
        return
      }
      this.currentIndex = this.currentIndex + 1
      this.currentQuestion = this.questionList[this.currentIndex]
      this.onChange()
    },
    /**
     * 右滑事件
     */
    mySwipeRight() {
      // 第一题不允许右滑
      if (!this.checkCurrentIndex(this.currentIndex - 1)) {
        return
      }
      this.currentIndex = this.currentIndex - 1
      this.currentQuestion = this.questionList[this.currentIndex]
      this.onChange()
    },
    /**
     * 获取当前题目的答题信息
     */
    onChange() {
      // 获取当前题号
      let index = this.currentIndex
      // 判断是否已经作答过
      this.currentSelected = []
      for (let i = 0; i < this.selected.length; ++i) {
        if (
          this.selected[i].questionNo == this.questionList[index].questionNo
        ) {
          this.currentSelected = this.selected[i].answer
          break
        }
      }
    },
    /**
     * 提交答案
     */
    async submitAnswer() {
      if (this.selected.length < this.questionList.length) {
        this.$toast.fail('请完成所有题目！')
        return
      }
      // 计算分值
      this.getTotalSocre()
      // 计算用时
      this.getTimeUsed()
      // scoreDetail: 题型:总提数:对题数
      let scoreDetail = ''
      Object.keys(this.questionType).forEach((name) => {
        let temp =
          name +
          ':' +
          this.partCorrectTotalNum[name] +
          ':' +
          this.partCorrectNum[name]
        scoreDetail = scoreDetail + temp + ';'
      })
      scoreDetail = scoreDetail.substring(0, scoreDetail.length - 1)

      let sessionId = this.sessionId
      // 构造请求参数
      let params = {
        sessionId: sessionId,
        bizContent: {
          eventNo: '00001',
          score: this.totalScore,
          scoreDetail: scoreDetail
        }
      }
      this.$toast.success('提交成功' + params)
    },
    /**
     * 选中答案触发
     * @param item 当前题目信息
     * @param name 题目选项
     */
    selectedAnswer(item, name) {
      // 更新当前选中值，以便修改样式
      this.updateCurrentSelected(item, name)
      // 更新当前所有选中列表
      this.updateSelectedList(item, name)
      // 更新完选项后，根据题型判断是否直接进入下一题
      // 单选题选中后直接进入下一题
      this.$nextTick(() => {
        setTimeout(() => {
          if (item.questionType == 1 && this.currentSelected.length > 0) {
            this.goNext(this.currentIndex + 1)
          }
        }, 200)
      })
    },
    /**
     * 更新当前选中值
     */
    updateCurrentSelected(item, name) {
      if (!this.currentSelected.includes(name)) {
        // 如果当前未选中，则置为选中状态
        if (item.questionType == 1) {
          // 单选题
          this.currentSelected.pop()
          this.currentSelected.push(name)
        } else if (item.questionType == 2) {
          //多选题
          this.currentSelected.push(name)
        }
      } else {
        // 如果当前已选中，则取消选中
        let index = 0
        for (let i = 0; i < this.currentSelected.length; ++i) {
          if (this.currentSelected[i] == name) {
            index = i
            break
          }
        }
        this.currentSelected.splice(index, 1)
      }
    },
    /**
     * 更新选中列表
     */
    updateSelectedList(item) {
      // 判断是否已经作答过
      let isSelected = false
      for (let i = 0; i < this.selected.length; ++i) {
        if (this.selected[i].questionNo == item.questionNo) {
          isSelected = true
          break
        }
      }
      if (isSelected) {
        // 若已经作答过，则用新值替换
        this.$set(
          this.selected[this.currentIndex],
          'answer',
          this.currentSelected
        )
        // 如果当前题目已经没有选中任何选项，则从选中列表中删除该项
        if (this.currentSelected.length == 0) {
          this.selected.splice(this.currentIndex, 1)
        }
      } else {
        // 若未作答过，则记录新值
        this.selected.push({
          questionNo: item.questionNo,
          answer: this.currentSelected
        })
      }
    },
    showTipInfoPopup() {
      this.tipInfoshow = !this.tipInfoshow
    },
    /**
     * 计算分值
     */
    getTotalSocre() {
      // 构造题号和分值对象
      let questionScoreObj = {}
      // 构造题号和正确答案对象
      let questionAnswerObj = {}
      // 构造题号和提醒对象
      let questionTypeObj = {}
      this.questionList.forEach((item) => {
        this.$set(questionScoreObj, item.questionNo, Number(item.questionScore))
        this.$set(questionAnswerObj, item.questionNo, item.answer)
        this.$set(questionTypeObj, item.questionNo, item.questionType)
      })
      // 总分值
      let totalScore = 0
      // 总对题数
      let totalCorrectNum = 0
      // 按题型统计分值
      let partScoreTotal = {
        1: 0,
        2: 0,
        3: 0,
        4: 0
      }
      // 按题型统计对题数
      let partCorrectNum = {
        1: 0,
        2: 0,
        3: 0,
        4: 0
      }
      //// 按题型统计总题数
      let partCorrectTotalNum = {
        1: 0,
        2: 0,
        3: 0,
        4: 0
      }
      this.selected.forEach((item) => {
        let qObj = questionAnswerObj[item.questionNo]
          .split('')
          .sort()
          .toString()
        let qObjA = item.answer.sort().toString()
        // 获取题型
        let type = questionTypeObj[item.questionNo]
        if (qObj == qObjA) {
          // 计算总分值
          totalScore += questionScoreObj[item.questionNo]
          // 计算总对题数
          totalCorrectNum += 1
          // 计算 按题型统计分值
          this.$set(
            partScoreTotal,
            type,
            partScoreTotal[type] + questionScoreObj[item.questionNo]
          )
          //计算 按题型统计对题数
          this.$set(partCorrectNum, type, partCorrectNum[type] + 1)
        }
        //计算 按题型统计总题数
        this.$set(partCorrectTotalNum, type, partCorrectTotalNum[type] + 1)
      })
      this.totalScore = totalScore
      this.totalCorrectNum = totalCorrectNum
      this.partScoreTotal = partScoreTotal
      this.partCorrectNum = partCorrectNum
      this.partCorrectTotalNum = partCorrectTotalNum
    },
    // 计算用时
    getTimeUsed() {
      let leftHour = this.$refs.countDownTime.timeData.hours
      let leftMinutes = this.$refs.countDownTime.timeData.minutes
      let leftSeconds = this.$refs.countDownTime.timeData.seconds
      let leftMilliseconds = this.$refs.countDownTime.timeData.milliseconds
      let totalLeftMilliseconds =
        leftMilliseconds +
        leftSeconds * 1000 +
        leftMinutes * 60 * 1000 +
        leftHour * 60 * 60 * 1000
      this.usedSeconds = (this.time - totalLeftMilliseconds) / 1000
    }
  }
}
</script>

<style lang="less" scoped>
.mainRow {
  background-color: #f2f2f2;
  height: 100%;
  padding: 0rem 0.25rem 0rem 0.25rem;
  // background-image: url("~@/assets/images/testBg.png");
  background-size: 100%100%;
  background-repeat: no-repeat;
  overflow-y: auto;
}
.topRow {
  margin: 0.3rem 0;
}
.colon {
  display: inline-block;
  margin: 0 4px;
  color: #1c90e8;
}
.block {
  display: inline-block;
  width: 22px;
  color: #fff;
  font-size: 12px;
  text-align: center;
  background-color: #1c90e8;
  border-radius: 0.1rem;
}

.selectedquestionClsss {
  /*height: 100%;*/
  background-color: #fff;
  border-radius: 0.3rem;
}
.questionDetailRow {
  background-color: #fff;
  border-radius: 0.5rem;
  max-height: 12rem;
  overflow-y: scroll;
}
.questionIndexRow {
  height: 0.6rem;
  padding: 0.4rem 0.3rem 0rem 0.2rem;
}

.questionTitle {
  min-height: 1rem;
  padding-left: 0.2rem;
  line-height: 0.6rem;
  font-size: 18px;
}
.selectAnswer {
  /*height: 1rem;*/
  padding: 0.28rem 0.28rem;
  margin: 0.2rem;
  border: 1px solid #f2f2f2;
  border-radius: 0.2rem;
  background-color: #fafafa;
}
.selectedAnswer {
  /*height: 1rem;*/
  padding: 0.28rem 0.28rem;
  margin: 0.2rem;
  border: 1px solid #f2f2f2;
  border-radius: 0.2rem;
  background-color: #7fddad;
}
.tipInfoBtnRow {
  margin-bottom: 0.3rem;
  padding-right: 0.3rem;
  font-size: 0.28rem;
  color: #a4937f;
}
.tipInfoCurrentAnswer {
  line-height: 0.6rem;
  padding: 0.2rem;
  color: #e81737;
}
.tipInfoRow {
  line-height: 0.64rem;
  padding: 0.2rem;
  height: 170px;
  overflow-y: scroll;
}
.departmentRow {
  height: 0.5rem;
  margin-top: 0.2rem;
  margin-left: 0.2rem;
}
.tipInfoCurrentText {
  width: 100%;
  max-height: 100%;
}
</style>